package UI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Class for Google Images API image retrieval.
 */
public class ImageGrabber 
{
	/**
	 * Searches for images matching the given query, and returns the URL of the first match.
	 * 
	 * @param query The query text
	 * @return The URL of the first image match
	 * @throws IOException
	 * @throws JSONException
	 */
	public static String searchImage(String query) throws IOException, JSONException
	{
		URL url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +
				"v=1.0&rsz=1&imgsz=small|medium&q=" + URLEncoder.encode(query, "UTF-8") +
				"&key=ABQIAAAAK3j5-AO63ViQMQl13q8vPxSYBjUD-Gp2fZNNZ8Mk62ODEnMyQBRuv_fJC4pDHImjUnnjc_TpACMFUg");
		
		URLConnection connection = url.openConnection();
		connection.addRequestProperty("Referer", "http://code.google.com/p/tau-db-2011/");
		
		String line = null;
		StringBuilder builder = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		
		while ((line = reader.readLine()) != null) 
		{
			builder.append(line);
		}
		
		JSONObject json = new JSONObject(builder.toString());
		JSONArray results = json.getJSONObject("responseData").getJSONArray("results");
		String imageUrl = null;
		
		if (results.length() > 0)
		{
			imageUrl = ((JSONObject)results.get(0)).getString("url");
		}
		
		return imageUrl;
	}
}
